package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.enums.FriendStatus;
import com.zenithmind.chat.mapper.ChatFriendMapper;
import com.zenithmind.chat.mapper.ChatFriendSettingMapper;
import com.zenithmind.chat.pojo.entity.ChatFriend;
import com.zenithmind.chat.pojo.entity.ChatFriendSetting;
import com.zenithmind.chat.pojo.vo.ChatFriendVO;
import com.zenithmind.chat.service.ChatFriendService;
import com.zenithmind.common.result.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatFriendServiceImpl extends ServiceImpl<ChatFriendMapper, ChatFriend> implements ChatFriendService {

    private final ChatFriendSettingMapper chatFriendSettingMapper;

    @Override
    public List<ChatFriendVO> getUserFriends(String userId, String keyword, Integer status) {
        log.debug("获取用户好友列表: userId={}, keyword={}, status={}", userId, keyword, status);

        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId);

        if (status != null) {
            wrapper.eq(ChatFriend::getStatus, FriendStatus.fromCode(status));
        }

        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(ChatFriend::getRemarkName, keyword)
                    .or().like(ChatFriend::getGroupName, keyword));
        }

        wrapper.orderByDesc(ChatFriend::getUpdateTime);

        List<ChatFriend> friends = list(wrapper);
        return convertToVOList(friends);
    }

    @Override
    public ChatFriendVO getFriendByUserId(String userId, String friendId) {
        log.debug("根据用户ID获取好友信息: userId={}, friendId={}", userId, friendId);

        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
                .eq(ChatFriend::getFriendId, friendId);

        ChatFriend friend = getOne(wrapper);
        return friend != null ? convertToVO(friend) : null;
    }

    @Override
    public Integer countFriends(String userId, Integer status) {
        log.debug("统计好友数量: userId={}, status={}", userId, status);

        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId);

        if (status != null) {
            wrapper.eq(ChatFriend::getStatus, FriendStatus.fromCode(status));
        }

        return Math.toIntExact(count(wrapper));
    }

    @Override
    public PageResult<ChatFriendVO> getFriendPage(String userId, String keyword, Integer status, Integer pageNum, Integer pageSize) {
        log.debug("分页查询好友列表: userId={}, keyword={}, status={}, pageNum={}, pageSize={}",
                userId, keyword, status, pageNum, pageSize);

        Page<ChatFriend> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId);

        if (status != null) {
            wrapper.eq(ChatFriend::getStatus, FriendStatus.fromCode(status));
        }

        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(ChatFriend::getRemarkName, keyword)
                    .or().like(ChatFriend::getGroupName, keyword));
        }

        wrapper.orderByDesc(ChatFriend::getUpdateTime);

        Page<ChatFriend> friendPage = page(page, wrapper);
        List<ChatFriendVO> voList = convertToVOList(friendPage.getRecords());

        return new PageResult<>(voList, friendPage.getTotal(), friendPage.getCurrent(), friendPage.getSize());
    }

    @Override
    public ChatFriendVO getFriendById(String friendId, String userId) {
        log.debug("根据好友ID获取好友信息: friendId={}, userId={}", friendId, userId);

        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
                .eq(ChatFriend::getFriendId, friendId);

        ChatFriend friend = getOne(wrapper);
        return friend != null ? convertToVO(friend) : null;
    }

    @Override
    public Boolean deleteFriend(String friendId, String userId) {
        log.debug("删除好友: friendId={}, userId={}", friendId, userId);

        LambdaUpdateWrapper<ChatFriend> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
                .eq(ChatFriend::getFriendId, friendId)
                .set(ChatFriend::getStatus, FriendStatus.DELETED);

        return update(wrapper);
    }

    @Override
    public Boolean updateFriendRemark(String friendId, String remark, String userId) {
        log.debug("更新好友备注: friendId={}, remark={}, userId={}", friendId, remark, userId);

        LambdaUpdateWrapper<ChatFriend> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
                .eq(ChatFriend::getFriendId, friendId)
                .set(ChatFriend::getRemarkName, remark);

        return update(wrapper);
    }

    @Override
    public Boolean updateFriendStatus(String friendId, Integer status, String userId) {
        log.debug("更新好友状态: friendId={}, status={}, userId={}", friendId, status, userId);

        LambdaUpdateWrapper<ChatFriend> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
                .eq(ChatFriend::getFriendId, friendId)
                .set(ChatFriend::getStatus, FriendStatus.fromCode(status));

        return update(wrapper);
    }

    @Override
    public Boolean batchDeleteFriends(List<String> friendIds, String userId) {
        log.debug("批量删除好友: friendIds={}, userId={}", friendIds, userId);

        if (friendIds == null || friendIds.isEmpty()) {
            return true;
        }

        LambdaUpdateWrapper<ChatFriend> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
                .in(ChatFriend::getFriendId, friendIds)
                .set(ChatFriend::getStatus, FriendStatus.DELETED);

        return update(wrapper);
    }

    @Override
    public Boolean checkFriendship(String userId, String targetUserId) {
        log.debug("检查好友关系: userId={}, targetUserId={}", userId, targetUserId);

        LambdaQueryWrapper<ChatFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriend::getUserId, userId)
                .eq(ChatFriend::getFriendId, targetUserId)
                .eq(ChatFriend::getStatus, FriendStatus.NORMAL);

        return count(wrapper) > 0;
    }

    @Override
    public List<ChatFriendVO> getMutualFriends(String userId, String targetUserId) {
        log.debug("获取共同好友: userId={}, targetUserId={}", userId, targetUserId);

        // 获取用户的好友列表
        LambdaQueryWrapper<ChatFriend> userFriendsWrapper = new LambdaQueryWrapper<>();
        userFriendsWrapper.eq(ChatFriend::getUserId, userId)
                .eq(ChatFriend::getStatus, FriendStatus.NORMAL);
        List<ChatFriend> userFriends = list(userFriendsWrapper);

        // 获取目标用户的好友列表
        LambdaQueryWrapper<ChatFriend> targetFriendsWrapper = new LambdaQueryWrapper<>();
        targetFriendsWrapper.eq(ChatFriend::getUserId, targetUserId)
                .eq(ChatFriend::getStatus, FriendStatus.NORMAL);
        List<ChatFriend> targetFriends = list(targetFriendsWrapper);

        // 找出共同好友
        List<String> userFriendIds = userFriends.stream()
                .map(ChatFriend::getFriendId)
                .collect(Collectors.toList());

        List<ChatFriend> mutualFriends = targetFriends.stream()
                .filter(friend -> userFriendIds.contains(friend.getFriendId()))
                .collect(Collectors.toList());

        return convertToVOList(mutualFriends);
    }

    /**
     * 将ChatFriend实体转换为ChatFriendVO
     */
    private ChatFriendVO convertToVO(ChatFriend friend) {
        if (friend == null) {
            return null;
        }

        ChatFriendVO vo = new ChatFriendVO();
        vo.setId(friend.getFriendId());
        vo.setRemarkName(friend.getRemarkName());
        vo.setStatus(friend.getStatus() != null ? friend.getStatus().getCode() : null);
        vo.setStatusText(friend.getStatus() != null ? friend.getStatus().getDescription() : null);
        vo.setGroupName(friend.getGroupName());
        vo.setAddTime(friend.getAddTime());
        vo.setAddSource(friend.getAddSource() != null ? friend.getAddSource().getDescription() : null);
        vo.setLastChatTime(friend.getLastChatTime());

        // 设置显示名称（备注名称优先，否则使用好友ID作为占位符）
        vo.setDisplayName(StringUtils.hasText(friend.getRemarkName()) ? friend.getRemarkName() : friend.getFriendId());

        // 获取好友设置信息
        ChatFriendSetting setting = chatFriendSettingMapper.getByUserIdAndFriendId(friend.getUserId(), friend.getFriendId());
        if (setting != null) {
            vo.setIsTop(setting.getIsTop() != null && setting.getIsTop() == 1);
            vo.setIsDisturbFree(setting.getIsDisturbFree() != null && setting.getIsDisturbFree() == 1);
        } else {
            vo.setIsTop(false);
            vo.setIsDisturbFree(false);
        }

        // 默认设置一些字段
        vo.setIsOnline(false); // 需要从其他服务获取在线状态

        return vo;
    }

    /**
     * 将ChatFriend实体列表转换为ChatFriendVO列表
     */
    private List<ChatFriendVO> convertToVOList(List<ChatFriend> friends) {
        if (friends == null || friends.isEmpty()) {
            return new ArrayList<>();
        }

        return friends.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }
}
